import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { MessageBox, Message } from 'element-ui'

NProgress.configure({showSpinner: false})

// 是否开启路由拦截
const enable = true;
// 路由白名单
const whiteList = ['/login','/redirect/redirect','/temp/index','/temp/gzhTransit','/temp/creditCardIncrease'];
// 是否登陆
const hasLogin = () => {
  return (store.getters.token!='' && store.getters.nickname!='' && store.getters.roleName!='')
}
// 是否存在菜单
const hasMenus = () => {
  return store.getters.menus.length > 0
}
// 是否显示标题白名单
const whiteTab = ['/temp/index','/temp/creditCardIncrease'];

router.beforeEach(async (to, fr, next) => {
  //console.log('to', to,' >>> fr',fr)

  if (enable) {
    NProgress.start()

    //拦截 ：没有登陆的 && 不再白名单
    if(!hasLogin() && whiteList.indexOf(to.path) === -1){
      try {
        store.commit('user/READ_SETTING_LOCAL_USER');
        if(!hasLogin()) throw new Error('未登陆');
      } catch (error) {
        //console.log('路由跳转校验时出现异常：',error)
        // Message.closeAll();
        // MessageBox.confirm('未登陆或登陆已超时，请重新登录', '登陆提醒', {
        //   confirmButtonText: '重新登陆',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // }).then(() => {
          store.dispatch('user/logout').then(r => {
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          })
        // })
        return;//出现异常就终止跳转
      }
    }

    //若登陆了但是没有角色菜单，那么加载角色菜单
    if(hasLogin() && !hasMenus()){
      //console.log("加载角色菜单 >>>")
      await store.dispatch('menu/loadMenuList');
    }

  }

  // if(whiteTab.indexOf(to.path)!==-1){
    document.title = to.meta.tab;
  // }

  next();
})

router.afterEach((to,fr) => {
  NProgress.done()
})
